<template>
  <div class="medical-clinic-search">
    <el-card shadow="hover" class="search-card">
      <h2>希望站医馆查询</h2>

      <!-- 表单 -->
      <el-form :model="searchForm" ref="searchFormRef" label-width="130px" :rules="rules">

        <el-row :gutter="20">
          <el-col :span="8">
            <el-form-item label="疾病科类" prop="diseaseCategory">
              <el-select v-model="searchForm.diseaseCategory" placeholder="请选择疾病科类" style="width: 100%">
                <el-option
                    v-for="item in diseaseCategories"
                    :key="item.value"
                    :label="item.label"
                    :value="item.value"
                />
              </el-select>
            </el-form-item>
          </el-col>

          <el-col :span="8">
            <el-form-item label="省市区" prop="address">
              <el-cascader
                  v-model="selectedOptions"
                  :options="cityOptions"
                  @change="handleChange"
                  placeholder="请选择省市区"
                  style="width: 100%"
                  clearable
              ></el-cascader>
            </el-form-item>
          </el-col>

          <el-col :span="8">
            <el-form-item label="疾病名称" prop="diseaseName">
              <el-input v-model="searchForm.diseaseName" placeholder="请输入疾病名称" />
            </el-form-item>
          </el-col>
        </el-row>

        <el-form-item>
          <el-button type="primary" @click="submitSearch">🔍 查询</el-button>
          <el-button @click="resetForm">🔄 重置</el-button>
          <el-button v-if="loading" loading>加载中...</el-button>
        </el-form-item>
      </el-form>

      <!-- 加载提示 -->
      <div v-if="loading" class="loading-message">
        正在查询，请稍候...
      </div>

      <!-- 搜索结果 -->
      <transition name="fade">
        <div v-show="clinics.length > 0 && !loading" class="search-results">
          <p>已检索到 {{ clinics.length }} 家医馆诊所</p>
          <ul>
            <li v-for="(clinic, index) in clinics" :key="index" class="clinic-item">
              <h3>{{ clinic.name }}</h3>
              <p><strong>医师名称：</strong>{{ clinic.doctorName }}</p>
              <p><strong>擅长主治：</strong>{{ clinic.specialty }}</p>
              <p><strong>医馆地址：</strong>{{ clinic.province }}{{ clinic.city }}{{ clinic.district }}{{ clinic.detailedAddress }}</p>
              <p><strong>站长备注：</strong>{{ clinic.remarks }}</p>
            </li>
          </ul>
        </div>
      </transition>
    </el-card>
  </div>
</template>

<script>
import cityData from '../assets/cityData';
import axios from "axios"; // 导入省市区数据

export default {
  name: 'MedicalClinicSearch',
  data() {
    return {
      searchForm: {
        diseaseCategory: '',
        address: '', // 存储省市区信息
        diseaseName: ''
      },
      selectedOptions: [], // 存储用户选择的省市区选项
      cityOptions: cityData,
      diseaseCategories: [
        { value: '内科', label: '内科' },
        { value: '外科', label: '外科' },
        { value: '中医', label: '中医' },
        { value: '儿科', label: '儿科' }
      ],
      clinics: [],
      loading: false,
      rules: {
        diseaseCategory: [{ required: true, message: '请选择疾病科类', trigger: 'change' }],
        address: [{ required: true, message: '请选择省市区', trigger: 'change' }],
        diseaseName: [{ required: true, message: '请输入疾病名称', trigger: 'blur' }]
      }
    };
  },
  methods: {
    async submitSearch() {
      this.$refs.searchFormRef.validate(async valid => {
        if (valid) {
          this.loading = true;

          this.searchForm.address = this.selectedOptions.join(' ');

          try {
            const res = await this.$axios.post('/api/search', this.searchForm);

            // 安全解码工具函数
            function safeDecode(str) {
              if (typeof str !== 'string') return str;
              try {
                return decodeURIComponent(escape(str));
              } catch (e) {
                return str;
              }
            }

            this.clinics = res.data.map(clinic => ({
              name: safeDecode(clinic.clinic_name),
              doctorName: safeDecode(clinic.doctor_name),
              specialty: safeDecode(clinic.specialty),
              detailedAddress: safeDecode(clinic.detailed_address),
              remarks: safeDecode(clinic.remarks),
              province: this.getRegionName(clinic.province),
              city: this.getRegionName(clinic.city),
              district: this.getRegionName(clinic.district)
            }));

            this.loading = false;
          } catch (error) {
            console.error('Error fetching clinics:', error);
            this.$message.error('查询失败，请稍后再试');
            this.loading = false;
          }
        } else {
          this.$message.error('请检查表单内容');
          return false;
        }
      });
    },
    resetForm() {
      this.$refs.searchFormRef.resetFields();
      this.selectedOptions = []; // 清空省市区选择
      this.clinics = [];
    },
    handleChange(value) {
      this.searchForm.address = value.join(' '); // 更新地址字段
    },
    getRegionName(code) {
      function findLabel(data, code) {
        for (let item of data) {
          if (item.value === code) {
            return item.label;
          }
          if (item.children) {
            const result = findLabel(item.children, code);
            if (result) return result;
          }
        }
        return '';
      }

      return findLabel(this.cityOptions, code);
    }
  }
};
</script>

<style scoped>
.medical-clinic-search {
  max-width: 1200px;
  margin: 40px auto;
  padding: 20px;
}

.search-card {
  padding: 20px;
  border-radius: 10px;
}

.search-results {
  margin-top: 30px;
  background-color: #f9f9f9;
  padding: 20px;
  border-radius: 8px;
}

.search-results ul {
  list-style-type: none;
  padding: 0;
}

.clinic-item {
  background-color: #fff;
  border: 1px solid #eee;
  border-radius: 6px;
  padding: 15px;
  margin-bottom: 15px;
  transition: box-shadow 0.3s ease;
}

.clinic-item:hover {
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
}

.loading-message {
  text-align: center;
  font-size: 16px;
  color: #606266;
  margin-top: 20px;
}

/* 动画效果 */
.fade-enter-active, .fade-leave-active {
  transition: opacity 0.5s ease;
}
.fade-enter, .fade-leave-to {
  opacity: 0;
}
</style>